﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.ComponentModel;
using System.Reflection;

namespace WebToolsClslib
{
    public class Login
    {
        /// <summary>验证，设置身份验证票据，否则输出返回出错提示
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="_page"></param>
        /// <param name="iAuth"></param>
        public static void FormValidate(string name, string pwd, System.Web.UI.Page _page, IAuthUser iAuth, bool needAuth)
        {
            name = name.Trim();
            pwd = pwd.Trim();
            if (needAuth)
            {
                if (iAuth != null)
                {
                    if (iAuth.AuthUser(name, pwd))
                    {
                        DoSetAuthUser(name, _page);
                    }
                    else
                    {
                        _page.Response.Write(@"<script>alert('你输入的有错')</script>");
                    }
                }
                else
                {
                    throw new ArgumentNullException("验证接口为空");
                }
            }
            else
            {
                DoSetAuthUser(name, _page);
            }
        }
          
        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] 
        private static void DoSetAuthUser(string name, System.Web.UI.Page _page)
        {
            if (name != null && name.Length > 0)
            {
                FormsAuthentication.SetAuthCookie(name, true);
                FormsAuthentication.RedirectFromLoginPage(name, true);
                //_page.Response.Redirect("~/Default.aspx");
            }
            else
            {
                _page.Response.Write(@"<script>alert('你输入的有错')</script>");
            }
        }

        /// <summary>生成md5密码
        /// 
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] 
        private string GenMD5Pwd(string pwd)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");
        }
    }
}
